/**
 *Copyright 2013 by dragon.
 *
 *File name: HttpDownLoader.java
 *Author:      dragon
 *Email:       fufulove2012@gmail.com
 *Blog:        http://blog.csdn.net/xidomlove
 *Version:     1.0.0
 *Date:        2013-10-4 下午3:44:25
 *Description: 
 */
package com.dragon.jaxel.xtp;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.dragon.log.Logger;

/**
 * @author dragon8
 * 
 */
public class HttpDownloader extends XtpDownloader {

	private String urlString;

	public HttpDownloader() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	public HttpDownloader(String urlString, String savePath) {
		// TODO Auto-generated constructor stub
		this.urlString = urlString;
		super.savePathString = savePath;
	}

	private HttpURLConnection connect(long rangeBegin) throws IOException {
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		connection
				.setRequestProperty(
						"User-Agent",
						"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36");

		connection.setRequestProperty("Range", "bytes=" + rangeBegin + "-");
		connection.setUseCaches(false); // 不使用缓存,否则由于多连接下载，缓存会只缓存一个连接的内容，下次下载只能下载到一个连接的内容！！
		connection.setConnectTimeout(15000);
		connection.connect();

		return connection;
	}

	@Override
	long getFileLength() {
		// TODO Auto-generated method stub
		try {
			HttpURLConnection connection = connect(0);

			// jdk7才支持,弃用并自己解析
			// long len = connection.getContentLengthLong();
			long len = -1;
			String contentLenthString = connection
					.getHeaderField("Content-Length");
			if (contentLenthString != null) {
				len = Long.valueOf(contentLenthString);
			} else if ((contentLenthString = connection
					.getHeaderField("Content-Range")) != null) {
				len = Long.valueOf(contentLenthString
						.substring(contentLenthString.lastIndexOf('/') + 1));
			} else {
				len = connection.getContentLength();
			}
			Logger.getDefaultLogger().info(
					"Http response code: " + connection.getResponseCode());
			connection.disconnect();
			return len;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.getDefaultLogger().info("Http connect failed");
		}
		return -1;
	}

	@Override
	InputStream openConnection(ConnectionContext context, long bytesBegin,
			long bytesEnd) throws IOException {
		// TODO Auto-generated method stub
		HttpURLConnection connection = connect(bytesBegin);
		context.tokenObject = connection;
		return connection.getInputStream();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dragon.jsnative.download.Downloader#closeConnection(com.dragon.jsnative
	 * .download.ConnectionContext, java.io.InputStream)
	 */
	@Override
	protected void closeConnection(ConnectionContext context)
			throws IOException {
		// TODO Auto-generated method stub
		super.closeConnection(context);
		HttpURLConnection connection = (HttpURLConnection) context.tokenObject;
		connection.disconnect();
	}

	@Override
	protected void saveDowanloadState(ObjectOutputStream outputStream)
			throws IOException {
		// TODO Auto-generated method stub
		outputStream.writeUTF(urlString);
	}

	@Override
	protected void loadDowanloadState(ObjectInputStream inputStream)
			throws IOException {
		// TODO Auto-generated method stub
		urlString = inputStream.readUTF();
	}

	@Override
	public String getProtocol() {
		// TODO Auto-generated method stub
		return "http";
	}

}
